package com.shanjupay.merchant.controller;

import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.common.util.PhoneUtil;
import com.shanjupay.common.util.SecurityUtil;
import com.shanjupay.merchant.api.AppService;
import com.shanjupay.merchant.api.MerchantService;
import com.shanjupay.merchant.api.dto.AppDTO;
import com.shanjupay.merchant.api.dto.MerchantDTO;
import com.shanjupay.merchant.convert.MerchantDetailConvert;
import com.shanjupay.merchant.convert.MerchantRegisterConvert;
import com.shanjupay.merchant.service.FileService;
import com.shanjupay.merchant.service.SmsService;
import com.shanjupay.merchant.vo.MerchantDetailVO;
import com.shanjupay.merchant.vo.MerchantRegisterVO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;
import java.io.IOException;

/**
 * <h1>Restful接口</h1>
 * @author lsy
 * @date 2020/05/06
 */
@RestController
@Api(value = "商户平台接口", tags = "商户平台接口", description = "商户平台应用接口")
@Slf4j
public class MerchantController {
    /**
     * 注入远程调用接口
     */
    @org.apache.dubbo.config.annotation.Reference
    MerchantService merchantService;

    @Autowired
    SmsService smsService;

    @Autowired
    FileService fileService;

    @Autowired
    AppService appService;

    @ApiOperation(value = "根据id查询用户商户信息")
    @GetMapping("/merchants/{id}")
    public MerchantDTO queryMerchantById(@PathVariable("id") Long id) {
        MerchantDTO merchantDTO = merchantService.queryMerchantById(id);
        return merchantDTO;
    }

    @ApiOperation("获取手机验证码")
    @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query")
    @GetMapping("/sms")
    public String getSMSCode(@RequestParam String phone) {
        log.info("向手机号：{}发送验证码", phone);
        return smsService.sendMsg(phone);
    }

    @ApiOperation("商户注册")
    @ApiImplicitParam(name = "merchantRegister", value = "注册信息", required = true,
            dataType = "MerchantRegisterVO", paramType = "body")
    @PostMapping("/merchants/register")
    public MerchantRegisterVO registerMerchant(@RequestBody MerchantRegisterVO merchantRegisterVO) {
        // 校验前端传来的数据
        if (merchantRegisterVO == null) {
            throw new BusinessException(CommonErrorCode.E_100108);
        }
        if (StringUtils.isBlank(merchantRegisterVO.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100112);
        }
        // 校验密码
        if (StringUtils.isBlank(merchantRegisterVO.getPassword())) {
            throw new BusinessException(CommonErrorCode.E_100111);
        }
        // 校验手机号
        if (!PhoneUtil.isMatches(merchantRegisterVO.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100109);
        }
        // 校验联系人非空
        if (StringUtils.isBlank(merchantRegisterVO.getUsername())) {
            throw new BusinessException(CommonErrorCode.E_100110);
        }
        // 校验验证码非空
        if (StringUtils.isBlank(merchantRegisterVO.getVerifyCode()) || StringUtils.isBlank(merchantRegisterVO.getVerifykey())) {
            throw new BusinessException(CommonErrorCode.E_100103);
        }


        // 校验验证码
        smsService.checkVerifyCode(merchantRegisterVO.getVerifykey(), merchantRegisterVO.getVerifyCode());
        MerchantDTO merchantDTO = MerchantRegisterConvert.INSTANCE.vo2dto(merchantRegisterVO);
        merchantService.createMerchant(merchantDTO);
        return merchantRegisterVO;
    }

    @ApiOperation("证件上传")
    @PostMapping("/upload")
    public String upload(@ApiParam(value = "上传文件", required = true) @RequestParam("file") MultipartFile multipartFile) throws IOException {
        // 原始文件
        String originFilename = multipartFile.getOriginalFilename();
        // 文件后缀
        String suffix = originFilename.substring(originFilename.lastIndexOf(".")-1);
        // 文件名称
        String filename = UUID.randomUUID().toString()+suffix;
        // 上传文件 返回文件下载url

        return fileService.upload(multipartFile.getBytes(), filename);
    }

    /**
     * 商户资质申请页面接口
     * @param merchantDetailVO {@link MerchantDetailVO}
     */
    @ApiOperation("商户资质申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "资质申请信息", value = "merchantDetailVO", required = true,
            dataType = "MerchantDetailVO", paramType = "body")
    })
    @PostMapping("/my/merchants/save")
    public void saveMerchant(@RequestBody MerchantDetailVO merchantDetailVO) {

        // 解析前端携带的Token得到商户id
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.vo2dto(merchantDetailVO);
        // 资质申请
        merchantService.applyMerchant(merchantId, merchantDTO);
    }

    /**
     * 查询商户App列表
     * @return {@link AppDTO}
     */
    @ApiOperation("查询商户下的应用列表")
    @GetMapping(value = "/my/apps")
    public List<AppDTO> queryMyApps() {
        // 根据Token获取的商户ID
        Long merchantId = SecurityUtil.getMerchantId();
        return appService.queryAppByMerchant(merchantId);

    }
}
